from decimal import Decimal

from django.contrib.auth.models import AbstractUser, Group
from django.db import models


class User(AbstractUser):
    email = None
    last_login = None
    REQUIRED_FIELDS = []

    def __init__(self, *args, email=None, **kwargs):
        super().__init__(*args, **kwargs)

    first_name = models.CharField(db_column='firstname', verbose_name="Имя",
                                  max_length=40, blank=False, null=False)
    second_name = models.CharField(db_column='secondname', verbose_name="Отчество",
                                   max_length=40, blank=True, null=True)
    last_name = models.CharField(db_column='lastname', verbose_name="Фамилия",
                                 max_length=40, blank=False, null=False)
    phone = models.CharField(verbose_name="Телефон", max_length=20,  blank=True, null=True)
    position = models.CharField(verbose_name="Должность", max_length=50, blank=True, null=True)
    image = models.ImageField(upload_to='images/', verbose_name="Фото", blank=True, null=True)

    first_login = models.BooleanField(default=False, verbose_name='Входил ли пользователь после смены пароля')
    user_modify = models.CharField(verbose_name="Логин изменившего учетную запись", blank=True, null=True)
    user_create = models.CharField(verbose_name="Логин создавшего запись", blank=True, null=True)
    create_date = models.DateTimeField(auto_now_add=True)
    update_date = models.DateTimeField(auto_now=True, db_column='modify_date')

    main_specialization = models.ForeignKey(
        'Specialization',
        related_name='main_specialization_users',
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        verbose_name="Основная специализация",
    )
    additional_specializations = models.ManyToManyField(
        'Specialization',
        related_name='additional_specialization_users',
        blank=True,
        verbose_name="Дополнительные специализации",
    )
    employment_fraction = models.DecimalField(
        verbose_name="Ставка",
        max_digits=3,
        decimal_places=2,
        choices=(
            (Decimal('0.10'), '0.10'),
            (Decimal('0.25'), '0.25'),
            (Decimal('0.50'), '0.50'),
            (Decimal('0.75'), '0.75'),
            (Decimal('1.00'), '1.00')
        ),
        default=Decimal('1.0'),
        blank=True,
        null=True
    )

    @property
    def formatted_additional_specializations(self):
        return ', '.join([str(spec) for spec in self.additional_specializations.all()])

    @property
    def is_doctor(self):
        return 'Врач' in [gr.name for gr in self.groups.all()]

    @property
    def is_hr(self):
        return 'Отдел кадров' in [gr.name for gr in self.groups.all()]

    @property
    def is_chief(self):
        return 'Руководитель референс-центра' in [gr.name for gr in self.groups.all()]

    @property
    def fio(self):
        return f' {self.last_name} {self.first_name} {self.second_name or ""}'

    def __str__(self):
        return (f"{self.fio}\n"
                f"{self.main_specialization or ''}\n"
                f"{self.formatted_additional_specializations}")

    class Meta:
        verbose_name = "Пользователь"
        verbose_name_plural = "Пользователи"
        ordering = ['first_name']


class Specialization(models.Model):
    specialization = models.TextField(verbose_name="Специализация", blank=False, null=False)

    class Meta:
        db_table = "specialization"

    def __str__(self):
        return self.specialization

class SpecializationType(models.Model):
    specialization = models.ForeignKey(Specialization, on_delete=models.CASCADE, related_name='types')
    type = models.TextField(verbose_name="Тип специализации", blank=False, null=False, default='')


    class Meta:
        db_table = "specialization_type"

    def __str__(self):
        return f"{self.specialization} {self.type}"